package com.example.volunteer.config;

import com.example.volunteer.model.Admin;
import com.example.volunteer.model.Volunteer;
import com.example.volunteer.service.AdminService;
import com.example.volunteer.service.VolunteerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service
public class CustomUserDetailsService implements UserDetailsService {

    private final VolunteerService volunteerService;
    private final AdminService adminService;

    @Autowired
    public CustomUserDetailsService(VolunteerService volunteerService, AdminService adminService) {
        this.volunteerService = volunteerService;
        this.adminService = adminService;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 根据ID前缀判断用户类型
        if (username.startsWith("V")) {
            Volunteer volunteer = volunteerService.findById(username);
            if (volunteer == null) {
                throw new UsernameNotFoundException("Volunteer not found with id: " + username);
            }
            return User.builder()
                    .username(volunteer.getVolunteerId())
                    .password(volunteer.getPassword())
                    .roles("VOLUNTEER")
                    .build();
        } else if (username.startsWith("A")) {
            Admin admin = adminService.findById(username);
            if (admin == null) {
                throw new UsernameNotFoundException("Admin not found with id: " + username);
            }
            return User.builder()
                    .username(admin.getAdminId())
                    .password(admin.getPassword())
                    .roles("ADMIN")
                    .build();
        } else {
            throw new UsernameNotFoundException("Invalid user type prefix: " + username);
        }
    }
}
